<template>
  <div class="content-app" data-request-interceptor>
    <!-- 浮动按钮 - 一直显示 -->
    <FloatingButton
      v-if="extensionEnabled"
      @click="toggleDialog"
    />

    <!-- 拦截器对话框 -->
    <InterceptorDialog
      v-if="isDialogVisible"
      @close="hideDialog"
      @open-editor="handleOpenEditor"
    />

    <!-- 编辑响应数据对话框 - 独立于拦截器对话框 -->
    <EditDialog
      :visible="editDialogVisible"
      :url="editingItem?.url"
      :method="editingItem?.method"
      :response-data="editingItem?.responseData"
      :is-new="!editingItem?.id"
      :item-id="editingItem?.id"
      :existing-params="editingItem?.editedParams"
      @close="closeEditDialog"
      @save="saveEdit"
    />

    <!-- 消息提示组件 -->
    <MessageToast />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useInterceptorStore } from '@/stores/interceptor'
import { ElMessage } from 'element-plus'
import FloatingButton from './components/FloatingButton.vue'
import InterceptorDialog from './components/InterceptorDialog.vue'
import EditDialog from './components/EditDialog.vue'
import MessageToast from './components/MessageToast.vue'

const store = useInterceptorStore()
const isDialogVisible = ref(false)
const extensionEnabled = ref(true)



// 监听来自popup的状态变化消息
const handleWebsiteStatusChange = (message) => {
  if (message.type === 'WEBSITE_STATUS_CHANGED') {
    console.log('📨 收到网站状态变化消息:', message)

    // 如果启用了拦截，重新注入拦截规则
    if (message.enabled) {
      console.log('🔄 网站已启用拦截，重新注入拦截规则...')
      console.log('📋 当前拦截规则数量:', store.interceptedRequests.length)
      store.updateInjectedScript()
    } else {
      console.log('❌ 网站已禁用拦截')
    }
  }
}



// 编辑对话框相关状态
const editDialogVisible = ref(false)
const editingItem = ref(null)

// 切换对话框显示状态
const toggleDialog = () => {
  isDialogVisible.value = !isDialogVisible.value
}

// 隐藏对话框
const hideDialog = () => {
  isDialogVisible.value = false
}

// 编辑对话框相关方法
const handleOpenEditor = (data) => {
  console.log("请求数据哦",data)
  // 直接使用原始请求头数据，不做任何默认处理
  const requestHeaders = data.requestHeaders

  editingItem.value = {
    id: data.id || null,
    url: data.url,
    method: data.method,
    responseData: data.responseData,
    editedParams: {
      urlParams: {},
      requestHeaders: requestHeaders,
      requestBody: data.requestBody || null
    }
  }
  editDialogVisible.value = true
}

const closeEditDialog = () => {
  editDialogVisible.value = false
  editingItem.value = null
}

// URL规范化函数 - 转换为相对路径格式
const normalizeUrlToRelative = (url) => {
  try {
    let urlObj

    // 如果已经是相对路径，直接返回
    if (url.startsWith('/')) {
      return url
    }

    // 如果是完整URL，提取路径和参数部分
    if (url.startsWith('http')) {
      urlObj = new URL(url)
      return urlObj.pathname + urlObj.search
    }

    // 其他情况直接返回
    return url
  } catch (error) {
    console.warn('URL规范化失败:', error, 'URL:', url)
    return url
  }
}

const saveEdit = async (data) => {
  if (!editingItem.value) {
    ElMessage.error('编辑项目不存在')
    return
  }

  try {
    // 规范化URL为相对路径格式
    const normalizedUrl = normalizeUrlToRelative(data.url)

    if (editingItem.value.id) {
      // 更新现有拦截规则
      store.updateInterceptRule(editingItem.value.id, {
        url: normalizedUrl,
        responseData: data.responseData,
        editedParams: data.editedParams
      })
      ElMessage.success('拦截规则更新成功！')
    } else {
      // 创建新的拦截规则
      const interceptItem = {
        id: Date.now(),
        url: normalizedUrl,
        method: editingItem.value.method,
        responseData: data.responseData,
        editedParams: data.editedParams,
        enabled: true
      }
      store.addInterceptRule(interceptItem)
      ElMessage.success('拦截规则创建成功！')
    }

    // 更新注入脚本
    store.updateInjectedScript()

    // 关闭编辑对话框
    closeEditDialog()

  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(`保存失败: ${error.message}`)
  }
}

// 注入拦截脚本 - 只在扩展启用时注入
const injectScript = () => {
  if (!extensionEnabled.value) {
    console.log('🚫 扩展已禁用，跳过JS注入')
    return
  }

  const script = document.createElement('script')
  script.src = chrome.runtime.getURL('src/injected.js')
  script.onload = () => {
    script.remove()
    console.log('🔧 Injected script loaded, sending current config...')
    setTimeout(() => {
      store.updateInjectedScript()
    }, 100)
  }
  ;(document.head || document.documentElement).appendChild(script)
  console.log('✅ 扩展已启用，JS脚本已注入')
}

// 设置消息监听器
const setupMessageListeners = () => {
  // 监听来自注入脚本的网络请求
  const handleMessage = (event) => {
    if (event.source !== window) return

    if (event.data.type === 'NEW_REQUEST') {
      store.addRequest(event.data.request)
      // 转发到background script
      chrome.runtime.sendMessage({
        type: 'NEW_REQUEST',
        request: event.data.request
      }).catch(() => {
        // 忽略错误
      })
    }
  }

  window.addEventListener('message', handleMessage)

  // 监听来自popup的消息
  const handleRuntimeMessage = (message) => {
    if (message.type === 'UPDATE_INTERCEPT_DATA') {
      store.updateInjectedScript(message.data)
    } else if (message.type === 'WEBSITE_STATUS_CHANGED') {
      handleWebsiteStatusChange(message)
    }
    return true
  }

  chrome.runtime.onMessage.addListener(handleRuntimeMessage)

  // 返回清理函数
  return () => {
    window.removeEventListener('message', handleMessage)
    chrome.runtime.onMessage.removeListener(handleRuntimeMessage)
  }
}

// 设置扩展状态监听器
const setupExtensionStatusListener = () => {
  const handleExtensionToggle = async (message) => {
    if (message.type === 'EXTENSION_STATE_CHANGED') {
      const oldState = extensionEnabled.value
      extensionEnabled.value = message.enabled
      console.log('🔧 扩展状态变化:', message.enabled ? '启用' : '禁用')

      // 如果从禁用变为启用，需要注入脚本和加载数据
      if (!oldState && message.enabled) {
        console.log('🔧 扩展被启用，注入脚本并加载数据')
        injectScript()
        await store.loadData()
        setTimeout(() => {
          checkAndInjectRules()
        }, 500)
      }
      // 如果从启用变为禁用，清理相关功能
      else if (oldState && !message.enabled) {
        console.log('🔧 扩展被禁用，清理功能')
        // 隐藏对话框
        isDialogVisible.value = false
        editDialogVisible.value = false
      }
    }
    return true
  }

  chrome.runtime.onMessage.addListener(handleExtensionToggle)

  return () => {
    chrome.runtime.onMessage.removeListener(handleExtensionToggle)
  }
}

let messageCleanup = null
let extensionCleanup = null

// 加载扩展状态
const loadExtensionState = async () => {
  try {
    const result = await chrome.storage.local.get(['extensionEnabled'])
    extensionEnabled.value = result.extensionEnabled !== false // 默认启用
    console.log('🔧 加载扩展状态:', extensionEnabled.value)
  } catch (error) {
    console.error('加载扩展状态失败:', error)
    extensionEnabled.value = true // 默认启用
  }
}

onMounted(async () => {
  console.log('🔧 Initializing Enhanced Content Script with Vue3...')

  // 1. 加载扩展状态
  await loadExtensionState()

  // 2. 设置消息监听器（总是需要监听状态变化）
  messageCleanup = setupMessageListeners()
  extensionCleanup = setupExtensionStatusListener()

  // 3. 根据状态决定是否注入拦截脚本
  if (extensionEnabled.value) {
    injectScript()

    // 4. 加载数据（只在启用时加载）
    await store.loadData()

    // 5. 等待一下确保数据完全加载，然后检查拦截规则
    setTimeout(() => {
      checkAndInjectRules()
    }, 500)
  }

  console.log('✅ Enhanced Content Script initialized successfully')
  console.log('💡 扩展状态:', extensionEnabled.value ? '启用' : '禁用')
  console.log('💡 悬浮按钮显示状态:', extensionEnabled.value ? '显示' : '隐藏')
})

// 检查并注入拦截规则的函数（简化版本，不按域名过滤）
const checkAndInjectRules = () => {
  const currentDomain = new URL(window.location.href).hostname
  console.log('🌐 当前网站域名:', currentDomain)
  console.log('📋 总拦截规则数量:', store.interceptedRequests.length)

  // 简化逻辑：只要有拦截规则就重新注入，不按域名过滤
  if (store.interceptedRequests.length > 0) {
    console.log(`🔄 发现有 ${store.interceptedRequests.length} 条拦截规则，重新注入拦截脚本...`)
    store.updateInjectedScript()

    // 列出具体的拦截规则
    store.interceptedRequests.forEach((rule, index) => {
      console.log(`  规则 ${index + 1}: ${rule.url}`)
    })
  } else {
    console.log('ℹ️ 暂无拦截规则')
  }
}

onUnmounted(() => {
  // 清理事件监听器
  if (messageCleanup) {
    messageCleanup()
  }
  if (extensionCleanup) {
    extensionCleanup()
  }
})
</script>

<style scoped>
.content-app {
  position: relative;
  pointer-events: none;
  /* 只重置可能冲突的属性，保留扩展自己的样式 */
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  box-sizing: border-box;
  z-index: 999999;
}

.content-app > * {
  pointer-events: auto;
}





/* 强制重置Element Plus组件样式，防止被网站CSS覆盖 */
.content-app :deep(.el-dialog) {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  z-index: 999999 !important;
}

.content-app :deep(.el-button) {
  font-family: inherit !important;
  box-sizing: border-box !important;
}

.content-app :deep(.el-input) {
  font-family: inherit !important;
  box-sizing: border-box !important;
}

.content-app :deep(.el-tabs) {
  font-family: inherit !important;
  box-sizing: border-box !important;
}

.content-app :deep(.el-overlay) {
  z-index: 999998 !important;
}
</style>
